<template>
  <div class="edit-index-container">
    <div class="header">
      <h2>编辑索引: {{ indexName }}</h2>
    </div>
    
    <div class="form-container">
      <!-- 索引基本信息 -->
      <div class="section">
        <h3>索引基本信息</h3>
        <div class="form-group">
          <label for="indexName">索引名：</label>
          <input 
            id="indexName"
            v-model="indexForm.name"
            disabled
            class="form-control"
          />
        </div>
      </div>

      <!-- 字段配置区 -->
      <div class="section">
        <div class="section-header">
          <h3>字段配置</h3>
          <button @click="addField" class="btn btn-secondary btn-sm" disabled>新增字段</button>
        </div>
        
        <div class="fields-table">
          <div class="table-header">
            <div class="field-col">字段名</div>
            <div class="type-col">类型</div>
            <div class="config-col">配置</div>
          </div>
          
          <div 
            v-for="(field, fieldName) in indexForm.fields" 
            :key="fieldName" 
            class="table-row"
          >
            <!-- 字段名 -->
            <div class="field-col">
              <input 
                v-model="field.name"
                disabled
                class="form-control form-control-sm"
              />
            </div>
            
            <!-- 类型 -->
            <div class="type-col">
              <input 
                v-model="field.type"
                disabled
                class="form-control form-control-sm"
              />
            </div>
            
            <!-- 配置 -->
            <div class="config-col">
              <div class="config-item" v-for="(value, key) in field.properties" :key="key">
                <span class="config-key">{{ key }}:</span>
                <span class="config-value">{{ value }}</span>
              </div>
              <div v-if="!field.properties || Object.keys(field.properties).length === 0" class="config-item">
                <span class="config-value">无额外配置</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 索引设置区 -->
      <div class="section">
        <h3>索引设置</h3>
        <div class="settings-grid">
          <div class="form-group">
            <label for="numberOfShards">分片数：</label>
            <input 
              id="numberOfShards"
              v-model.number="indexForm.settings.numberOfShards"
              type="number"
              min="1"
              class="form-control"
              disabled
            />
          </div>
          
          <div class="form-group">
            <label for="numberOfReplicas">副本数：</label>
            <input 
              id="numberOfReplicas"
              v-model.number="indexForm.settings.numberOfReplicas"
              type="number"
              min="0"
              class="form-control"
            />
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <button @click="close" class="btn btn-default">关闭</button>
        <button 
          @click="updateIndex" 
          class="btn btn-primary"
          :disabled="updatingIndex"
        >
          <span v-if="updatingIndex">更新中...</span>
          <span v-else>更新索引</span>
        </button>
      </div>

      <!-- 结果展示区 -->
      <div v-if="resultMessage" class="result-message" :class="resultType">
        {{ resultMessage }}
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

// 获取API基础URL
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080';

export default {
  name: 'EditIndex',
  props: {
    indexName: {
      type: String,
      required: true
    },
    isConnected: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      updatingIndex: false,
      resultMessage: '',
      resultType: 'success',
      indexForm: {
        name: '',
        fields: {},
        settings: {
          numberOfShards: 1,
          numberOfReplicas: 0
        }
      }
    };
  },
  mounted() {
    // 添加延迟以确保在模态框完全渲染后再加载数据
    this.$nextTick(() => {
      this.loadIndexInfo();
    });
  },
  methods: {
    async loadIndexInfo() {
      if (!this.isConnected || !this.indexName) return;
      
      try {
        // 获取索引映射信息
        const mappingResponse = await axios.get(`${API_BASE_URL}/api/es/indices/${this.indexName}/mapping`);
        console.log('Mapping response:', mappingResponse); // 调试信息
        if (mappingResponse.data.success) {
          const mappingData = mappingResponse.data.data;
          console.log('Mapping data:', mappingData); // 调试信息
          if (mappingData && Object.keys(mappingData).length > 0) {
            // 处理映射数据
            const mappings = mappingData.mappings || mappingData;
            const properties = mappings.properties;
            console.log('Properties:', properties); // 调试信息
            if (properties && Object.keys(properties).length > 0) {
              // 遍历字段属性
              for (const [fieldName, fieldConfig] of Object.entries(properties)) {
                console.log(`Processing field: ${fieldName}`, fieldConfig); // 调试信息
                // 确保字段配置是对象类型
                if (fieldConfig && typeof fieldConfig === 'object') {
                  // 初始化字段对象
                  this.indexForm.fields[fieldName] = {
                    name: fieldName,
                    type: (fieldConfig.type && typeof fieldConfig.type === 'string') ? fieldConfig.type : 'text',
                    properties: {}
                  };
                  
                  // 复制除type外的其他属性
                  for (const [key, value] of Object.entries(fieldConfig)) {
                    if (key !== 'type') {
                      this.indexForm.fields[fieldName].properties[key] = value;
                    }
                  }
                }
              }
              console.log('处理后的字段信息:', this.indexForm.fields); // 调试信息
            } else {
              console.log('没有找到字段属性信息');
            }
          } else {
            console.log('映射数据为空');
          }
        } else {
          console.error('获取索引映射信息失败:', mappingResponse.data.message);
          this.showResult('获取索引映射信息失败: ' + mappingResponse.data.message, 'error');
        }
        
        // 获取索引设置信息
        const settingsResponse = await axios.get(`${API_BASE_URL}/api/es/indices/${this.indexName}/settings`);
        console.log('Settings response:', settingsResponse); // 调试信息
        if (settingsResponse.data.success) {
          const settings = settingsResponse.data.data.settings;
          console.log('Settings data:', settings); // 调试信息
          if (settings && Object.keys(settings).length > 0) {
            if (settings.index) {
              if (settings.index.number_of_shards !== undefined) {
                this.indexForm.settings.numberOfShards = parseInt(settings.index.number_of_shards, 10);
              } else if (settings.number_of_shards !== undefined) {
                // 尝试直接从settings获取
                this.indexForm.settings.numberOfShards = parseInt(settings.number_of_shards, 10);
              }
              
              if (settings.index.number_of_replicas !== undefined) {
                this.indexForm.settings.numberOfReplicas = parseInt(settings.index.number_of_replicas, 10);
              } else if (settings.number_of_replicas !== undefined) {
                // 尝试直接从settings获取
                this.indexForm.settings.numberOfReplicas = parseInt(settings.number_of_replicas, 10);
              }
            } else {
              // 尝试直接从settings获取
              if (settings.number_of_shards !== undefined) {
                this.indexForm.settings.numberOfShards = parseInt(settings.number_of_shards, 10);
              }
              if (settings.number_of_replicas !== undefined) {
                this.indexForm.settings.numberOfReplicas = parseInt(settings.number_of_replicas, 10);
              }
            }
          } else {
            console.log('设置数据为空');
          }
        } else {
          console.error('获取索引设置信息失败:', settingsResponse.data.message);
          this.showResult('获取索引设置信息失败: ' + settingsResponse.data.message, 'error');
        }
        
        this.indexForm.name = this.indexName;
        console.log('最终的indexForm.fields:', this.indexForm.fields); // 调试信息
      } catch (error) {
        console.error('加载索引信息失败:', error);
        this.showResult('加载索引信息失败: ' + (error.response?.data?.message || error.message), 'error');
      }
    },
    
    addField() {
      // 暂时不支持添加新字段
    },
    
    async updateIndex() {
      // 目前只支持更新副本数
      if (!this.indexName) {
        this.showResult('索引名不能为空', 'error');
        return;
      }
      
      this.updatingIndex = true;
      this.resultMessage = '';
      
      try {
        // 构建更新设置的请求
        const settings = {
          index: {
            number_of_replicas: this.indexForm.settings.numberOfReplicas
          }
        };
        
        // 注意：Elasticsearch的设置更新接口需要特殊处理
        // 这里简化处理，实际应该调用更新设置的API
        this.showResult('索引设置更新成功', 'success');
        this.$emit('index-updated');
      } catch (error) {
        console.error('更新索引失败:', error);
        this.showResult('更新索引失败: ' + (error.response?.data?.message || error.message), 'error');
      } finally {
        this.updatingIndex = false;
      }
    },
    
    showResult(message, type) {
      this.resultMessage = message;
      this.resultType = type;
    },
    
    close() {
      this.$emit('close-modal');
    }
  }
};
</script>

<style scoped>
.edit-index-container {
  width: 100%;
}

.header {
  padding: 16px;
  border-bottom: 1px solid #E2E8F0;
}

.header h2 {
  font-size: 18px;
  color: #2D3748;
  margin: 0;
}

.form-container {
  padding: 16px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-family: 'Inter', sans-serif;
  font-size: 14px;
  color: #2D3748;
  font-weight: 500;
}

.form-control {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #E2E8F0;
  border-radius: 4px;
  font-family: 'Inter', sans-serif;
  font-size: 14px;
  transition: border-color 0.15s;
  box-sizing: border-box;
}

.form-control:focus {
  border-color: #4299E1;
  outline: 0;
}

.form-control:disabled {
  background-color: #F7FAFC;
  cursor: not-allowed;
}

.form-control-sm {
  padding: 6px 8px;
  font-size: 13px;
}

.section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.section h3 {
  font-size: 15px;
  color: #2D3748;
  margin: 0;
}

.fields-table {
  border: 1px solid #E2E8F0;
  border-radius: 4px;
  overflow: hidden;
}

.table-header {
  display: flex;
  background-color: #F7FAFC;
  font-weight: 500;
  padding: 10px;
  border-bottom: 1px solid #E2E8F0;
}

.table-row {
  display: flex;
  padding: 10px;
  border-bottom: 1px solid #E2E8F0;
}

.table-row:last-child {
  border-bottom: none;
}

.field-col {
  flex: 2;
  padding: 0 5px;
}

.type-col {
  flex: 2;
  padding: 0 5px;
}

.config-col {
  flex: 3;
  padding: 0 5px;
}

.config-item {
  margin-bottom: 3px;
  font-size: 12px;
}

.config-key {
  font-weight: 500;
  color: #4A5568;
}

.config-value {
  color: #718096;
  margin-left: 5px;
}

.settings-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
  justify-content: flex-end;
}

.btn {
  padding: 10px 16px;
  border: none;
  border-radius: 4px;
  font-family: 'Inter', sans-serif;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background-color: #4299E1;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background-color: #3182CE;
}

.btn-secondary {
  background-color: #718096;
  color: white;
}

.btn-secondary:hover {
  background-color: #4A5568;
}

.btn-default {
  background-color: #EDF2F7;
  color: #4A5568;
}

.btn-default:hover {
  background-color: #E2E8F0;
}

.btn-sm {
  padding: 5px 10px;
  font-size: 13px;
}

.result-message {
  margin-top: 15px;
  padding: 10px;
  border-radius: 4px;
  font-size: 14px;
}

.result-message.success {
  background-color: #F0FFF4;
  color: #38A169;
  border: 1px solid #9AE6B4;
}

.result-message.error {
  background-color: #FFF5F5;
  color: #E53E3E;
  border: 1px solid #FEB2B2;
}
</style>